# import mysql.connector
 
# # 连接到 MySQL 数据库
# connection = mysql.connector.connect(
#     host="localhost",       # MySQL 主机（本地为 localhost）
#     user="root",            # MySQL 用户名
#     password="password",    # MySQL 密码
#     database="test_db"      # 要连接的数据库
# )
 
# # 检查连接是否成功
# if connection.is_connected():
#     print("成功连接到数据库")


import pymysql
 
# # 连接到 MySQL 数据库
# connection = pymysql.connect(
#     host="localhost",       # MySQL 主机
#     user="root",            # 用户名
#     password="password",    # 密码
#     database="test_db"      # 数据库名
# )
 
# # 检查连接是否成功
# if connection.open:
#     print("成功连接到数据库")


# cursor = connection.cursor()
 
# # 创建一个名为 users 的表
# create_table_query = """
# CREATE TABLE IF NOT EXISTS users (
#     id INT AUTO_INCREMENT PRIMARY KEY,
#     name VARCHAR(50) NOT NULL,
#     age INT NOT NULL,
#     email VARCHAR(100) UNIQUE NOT NULL
# )
# """
# cursor.execute(create_table_query)
# print("表已创建")


# 插入单条记录
# insert_query = "INSERT INTO users (name, age, email) VALUES (%s, %s, %s)"
# data = ("Alice", 25, "alice@example.com")
# cursor.execute(insert_query, data)
 
# # 提交更改
# connection.commit()
# print("数据已插入")


# 插入多条记录
bulk_data = [
    ("Bob", 30, "bob@example.com"),
    ("Charlie", 35, "charlie@example.com"),
    ("David", 40, "david@example.com")
]
cursor.executemany(insert_query, bulk_data)
connection.commit()
print("批量数据已插入")


# 查询所有记录
select_query = "SELECT * FROM users"
cursor.execute(select_query)

# 获取所有结果
results = cursor.fetchall()
for row in results:
    print(row)


# 查询特定条件的数据
condition_query = "SELECT * FROM users WHERE age > %s"
cursor.execute(condition_query, (30,))
 
# 获取结果
results = cursor.fetchall()
for row in results:
    print(row)

# 更新用户的年龄
update_query = "UPDATE users SET age = %s WHERE name = %s"
cursor.execute(update_query, (28, "Alice"))
 
# 提交更改
connection.commit()
print("数据已更新")


import mysql.connector
 
# 连接到 MySQL 数据库
connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="password",
    database="test_db"
)
 
cursor = connection.cursor()
 
# 创建表
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL,
    age INT NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL
)
""")
 
# 插入数据
insert_query = "INSERT INTO users (name, age, email) VALUES (%s, %s, %s)"
cursor.execute(insert_query, ("Alice", 25, "alice@example.com"))
connection.commit()
 
# 查询数据
cursor.execute("SELECT * FROM users")
for row in cursor.fetchall():
    print(row)
 
# 更新数据
cursor.execute("UPDATE users SET age = %s WHERE name = %s", (26, "Alice"))
connection.commit()
 
# 删除数据
cursor.execute("DELETE FROM users WHERE name = %s", ("Alice",))
connection.commit()
 
# 关闭连接
cursor.close()
connection.close()